#!/usr/bin/php5
<?PHP

function main()
{
    if (!extension_loaded("sdl")) {
       if (!dl("sdl.so"))
           die("sdl扩展加载失败!\n");
    }

    SDL_Init(SDL_INIT_VIDEO);

    $screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
    $bg = SDL_LoadBMP("./backGround.bmp");
    $img = SDL_LoadBMP("./player.bmp");

    SDL_SetColorKey($img, SDL_SRCCOLORKEY, SDL_MapRGB($img['format'], 247, 0, 255));

    // SDL_BlitSurface($img, NULL, $bg, NULL);
    SDL_BlitSurface($bg, NULL, $screen, NULL);

    $src = [
        'x' => 0,
        'y' => 0,
        'w' => 48,
        'h' => 48
    ];

    $dst = [
        'x' => 350,
        'y' => 100
    ];
    SDL_BlitSurface($img, $src, $screen, $dst);


    SDL_Flip($screen);

    $p = 1;
    $y = 100;


    while (TRUE)
    {
        if (SDL_WaitEvent($event))
        {
            if ($event['type'] == SDL_QUIT)
                break;
            else if ($event['type'] == SDL_KEYDOWN)
            {
                if ($event['key']['keysym']['sym'] == 27)
                    break;
            }
            else if ($event['type'] == SDL_MOUSEMOTION)
            {
                // printf("x = %d, y = %d\n", $event['motion']['x'], $event['motion']['y']);
            }
            else if ($event['type'] == SDL_MOUSEBUTTONDOWN)
            {
                if ($event['button']['button'] == SDL_BUTTON_LEFT)
                {
                    SDL_BlitSurface($bg, NULL, $screen, NULL);
                    $src = [
                        'x' => 0,
                        'y' => $p++ * 48,
                        'w' => 48,
                        'h' => 48
                    ];

                    printf("p = %d\n", $p);

                    if ($p == 2)
                        $p = 0;

                    $dst = [
                        'x' => 350,
                        'y' => $y += 10,
                    ];
                    SDL_BlitSurface($img, $src, $screen, $dst);

                    SDL_Flip($screen);

                }
            }
        }
    }

    SDL_Quit();

    return 0;
}

exit(main());

